/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package requeteur;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import model.DBWriter;

/**
 *
 * @author Cyril
 */
public class ScoreByParagraphCalculator {
    //stocke le score pour chaque idNoeud
    private HashMap<Integer,Double> nodesScore;
    private DBWriter db;
    private ArrayList<Paragraphe> results;
    
    public ScoreByParagraphCalculator(DBWriter db) {
        this.nodesScore = new HashMap<Integer,Double>();
        this.db = db;
        this.results = new ArrayList<Paragraphe>();
    }
    
    //ajoute les scores d'un terme
    public void addScoresOfTerme(String t) {
        HashMap<Integer,Double> poids;
        poids = db.getPositionsOfTerme(t);
        this.addToNodesScore(poids);
    }
    
    //ajoute les poids du noeud aux scores globaux déjà calculés
    private void addToNodesScore(HashMap<Integer,Double> poids) {
        Set<Integer> nodes = poids.keySet();
        for (Integer node : nodes) {
            if (this.nodesScore.containsKey(node)) {
                this.nodesScore.put(node, this.nodesScore.get(node)+poids.get(node));
            } else {
                this.nodesScore.put(node, poids.get(node));
            }
        }
    }
    
    //retourne les nb meilleurs paragraphes
    public void calculResults() {            
        for(Integer id : this.nodesScore.keySet()) {
            results.add(new Paragraphe(id, this.nodesScore.get(id)));
        }
        Collections.sort(results);
    } 
    
    public ArrayList<Paragraphe> getSortedResults(int nb) {
        ArrayList<Paragraphe> res = new ArrayList<Paragraphe>();

        for (int i = 0; i<nb && i<results.size(); i++) {
            Paragraphe p = results.get(i);
            p.setXPathWithBD(db);
            p.setDocumentIdWithBD(db);
            res.add(p);
        }
        return res;
    }
}
